package org.lib.ws;

import java.io.IOException;
import java.util.Date;
import java.util.function.Consumer;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/**
 * 第一个websocket
 * 前后端交互的类实现消息的接收推送(自己发送给自己)
 * @author ben
 * @date 2021-11-11 21:38:38 CST
 */
@Component
@ServerEndpoint(value = "/ws1")
public class Endpoint1 {

	private Consumer<Object> cs = System.out::println;
	
	/**
	 * 连接建立成功调用的方法
	 * @author ben
	 * @date 2021-11-12 20:57:13 CST
	 * @param session
	 */
	@OnOpen
	public void onOpen(Session session) {
		cs.accept("onOpen session=" + session);
	}
	
	/**
	 * 连接关闭调用的方法
	 * @author ben
	 * @date 2021-11-12 20:57:21 CST
	 * @param session
	 */
	@OnClose
	public void onClose(Session session) {
		cs.accept("onClose session=" + session);
	}
	
	/**
	 * 收到客户端消息后调用的方法
	 * @author ben
	 * @date 2021-11-12 20:57:28 CST
	 * @param message 客户端发送过来的消息
	 * @param session
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		cs.accept("onMessage message=" + message + ", " + session.getId());
		
		// 回复消息
		this.sendMessage(session, "Reply: " + message + ", @" + new Date());
	}
	
	/**
	 * 发生错误时处理
	 * @author ben
	 * @date 2021-11-12 20:57:47 CST
	 * @param session
	 * @param err
	 */
	@OnError
	public void onError(Session session, Throwable err) {
		cs.accept("onError session.id=" + session.getId() + ", e.msg" + err.getMessage() + ", e.type=" + err.getClass());
	}

	/**
	 * 回复消息
	 * @author ben
	 * @date 2021-11-11 21:18:44 CST
	 * @param session
	 * @param reply
	 */
	private void sendMessage(Session session, String reply) {
		try {
			cs.accept("sendMessage:");
			session.getBasicRemote().sendText(reply);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
